<?php

trait demoTrait{


    # === tmp =========================================== 

    function vrListAct(){ 
        $fp = uval('fp');
        if($fp){ Debug::vrView(); }
        else{ Debug::vrList(); }
    }

   # === Exception =========================================== 

    function uexpAct(){
        $data = ['act'=>__function__, 'msg'=>'uexpAct.微框架'];
        abort("throw-Exception by Peace!", 688);
        //throw new Exception("throw-Exception by Peace!", 688);
        echo ".After Exception";
    }

    # === 显示模式 =========================================== 

    function json1Act(){ global $_cbase; 
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->api($data);
    }
    function html2Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tpl($data);
    }
    function xml3Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tpl($data, 'xml3.xml');
    }
    function notplAct(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tpl($data , 'notpl-'.date('Ymd'));
    }

    function varsAct(){
        $data = ['act'=>__function__, 'msg'=>'这些数据，从控制器返回'];
        $this->tpl($data);
    }

    # === 提示信息 =========================================== 

    function tipA1Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->api($data, 0, '状态OK');
    }
    function tipA2Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->api($data, 'No-Perm', 'XX1无权限', 601);
    }
    function tipB1Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tip($data, 0, '状态OK'); 
    }
    function tipB2Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tip($data, 'No-Perm', 'XX1无权限', 403);
    }
    function tipB3Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        $this->tip($data, 'No-Perm', 'XX1无权限', 403, 'root/_pub/info.xml');
    }
    function tipC1Act(){
        $errmsg = '最简单的.....状态OK';
        // $this->tip(errmsg:$errmsg); // 不用php8才支持的命名参数
        $this->tip($errmsg); 
    }

    # === States =========================================== 

    function successAct(){
        echo "success";
    }
    function failAct(){
        echo "fail";
    }
    function uhtmAct(){
        $data = "<h3>".__function__."</h3><p>ysKit.微框架</p>";
        echo "$data";
    }
    function ujsonAct(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.微框架'];
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    # === Classes =========================================== 

    function extendAct(){ 
        demoExt1::act2();
    }

    function httpAct(){
        $data = ['act'=>__function__, 'msg'=>'http.Class'];

        $url1 = 'http://localhost/peace/Im-Temp/MiniFrame/index.php/api/demo-httpRes';
        $url2 = 'https://www.baidu.com/img/flexible/logo/pc/peak-result.png?sss'; 
        $url3 = 'http://txjia.com/imcat/';
        $url4 = 'http://txjia.com/peace/index.htm';
        $url5 = DIR_DATA.'/db/ysKit.sqlite';
        $url6 = 'http://txjia.com/imcat/home.php?cargo&stype=a1015&order=click&keywd=%E5%8D%8E%E4%B8%BA';
        $ua = "Mozilla/8.8 (win ysKit-http ".Basic::kidRand().") Chrome/888.8 Safari/888.88";
        $ref = 'http://baidu.com/';
        $xml = "<root><id>peace</id><pass>".Basic::kidRand()."</pass></root>";
        $post = ['c'=>'d', 'msg'=>'中文'];

        $stab = ['doCurl','doFile']; // 'doSocket',
        $sact = 'doCurl'; Http::setCache(30);
        {
            $a1 = Http::$sact("$url2?a=tx0", 0, []);                        $data["$sact-img"] = strlen($a1);
            $a1 = Http::$sact("$url3?a=tx2", 0, []);                        $data["$sact-page3"] = strlen($a1);
            $a1 = Http::$sact("$url4", 0, []);                              $data["$sact-page4"] = strlen($a1);
            $a1 = Http::$sact("$url6", 0, []);                              $data["$sact-baiso"] = strlen($a1);

            $a1 = Http::$sact("$url1?a=6", 1, $post, ['User-Agent'=>$ua]);  $data["$sact-ua"] = json_decode($a1);
            $a1 = Http::$sact("$url1?a=5", 1, $post, ['ref'=>$ref]);        $data["$sact-ref"] = json_decode($a1);

            $a1 = Http::$sact("$url1?a=4", 1, $post, ['type'=>'json']);     $data["$sact-json"] = json_decode($a1);
            $a1 = Http::$sact("$url1?a=3", 1, $xml,  ['type'=>'xml']);      $data["$sact-xml"] = json_decode($a1);

            $a1 = Http::$sact("$url1?a=2", 0, $post);                       $data["$sact-get"] = json_decode($a1);
            $a1 = Http::$sact("$url1?a=1", 1, $post);                       $data["$sact-post"] = json_decode($a1);
        }
        #$res = Http::downLoad($url5, './imcat-logo.sqlite');
        #$res = Http::downSave($url4, './imcat-link.htm'); 
        $data["-end"] = '.end.';
        $this->api($data);
    }
    function httpResAct(){
        $data = ['act'=>__function__];

        $data['_ref'] = uval('HTTP_REFERER', '(null)', 's');
        $data['_ua'] = uval('HTTP_USER_AGENT', '(null)', 's'); 
        $data['_method'] = $_SERVER['REQUEST_METHOD'];

        $data['_get'] = $_GET;
        $data['_post'] = $_POST;
        $data['_input'] = file_get_contents("php://input");

        $this->api($data);
    }

    function fsopAct(){
        $data = ['act'=>__function__, 'msg'=>'fsop.Class'];

        $data["statDir-a2"] = $s2 = Fsop::statDir(DIR_YSKIT);

        $this->api($data);
    }

    function encodeAct(){
        $data = ['act'=>__function__, 'msg'=>'encode.Class'];

        $data["urlBase64-a1"] = $s1 = Encode::urlBase64('abc中文汉字123');
        $data["urlBase64-a2"] = $s2 = Encode::urlBase64($s1, 1);
        $data["urlBase64-b1"] = $s1 = Encode::urlBase64('!()+,-.;@^_~'); // `
        $data["urlBase64-b2"] = $s2 = Encode::urlBase64($s1, 1);
        $data["urlBase64-c1"] = $s1 = Encode::urlBase64('!()+,-.;@字');
        $data["urlBase64-c2"] = $s2 = Encode::urlBase64($s1, 'a');

        $data["urlEncode-a1"] = Encode::urlEncode('http://txjia.com/file.php/mod-key?a=b&p=abc中文汉字123');
        $data["sysPass-a1"] = Encode::sysPass('root', '123456', $mod='test');

        $data["sysRevert-a1"] = $s1 = Encode::sysRevert('abc中文汉字123');
        $data["sysRevert-a2"] = $s2 = Encode::sysRevert($s1, 1);

        $data["jwtMake-a1"] = $s1 = Encode::jwtMake(['uid'=>'admin', 'uname'=>'中文汉字123']);
        $data["jwtMake-a2"] = $s2 = Encode::jwtCheck($s1);

        $data["jwtMake-b1"] = $s1 = Encode::jwt(['uid'=>'admin', 'uname'=>'中文汉字123']);
        $data["jwtMake-b2"] = $s2 = Encode::jwt($s1);

        #$s3 = 'Qf3QTN0IDO4UjNxojIwhXZiwiIzITMX2a5JGr5Hap5tiL5iojIl1WYuVnIsIibp1GZhJiOiQWa1Jye';
        #$data["test-a1"] = Encode::sysRevert($s3, 1);
        #$data["test-a2"] = Encode::urlBase64(strrev($s3), 1);
        ##$data["test-a2"] = Encode::urlBase64($s3, 1);

        #peacexie\yskit\demoExt1::act2();

        #Debug::log('encode', $data);
        $this->api($data);
    }

    function convAct(){
        $data = ['act'=>__function__, 'msg'=>'conv.Class'];

        $data["c-autoCSet"] = Encode::autoCSet('abc中文汉字123'); // , 'utf-8', 'gbk'

        $data["c-jf1"] = Encode::jfMain('abc简繁体转换123', 'j2f');
        $data["c-jf2"] = Encode::jfMain('abc簡繁體轉換123', 'f2j');

        $data["c-py1a"] = Encode::pyOne('拼');
        $data["c-py1b"] = Encode::pyOne('音');
        $data["c-py-0"] = Encode::pyMain('中文汉字拼音', 0);
        $data["c-py-1"] = Encode::pyMain('简繁体转换拼音', 1);
        $data["c-py-9"] = Encode::pyMain('簡繁體轉換拼音', 9);

        $this->api($data);
    }

    function cbasicAct(){
        $data = ['act'=>__function__, 'msg'=>'basic.Class'];
        for($i=2;$i<15;$i++){
            $vk = Vcode::strRand($i); $vv = Basic::strMask($vk);
            $data[$vk] = strlen($vk) . " - " . $vv;
        }
        for($i=2;$i<15;$i++){
            $vk = Vcode::strRand($i)."@163.com"; $vv = Basic::strMask($vk);
            $data["$vk-email"] = strlen($vk) . " - " . $vv;
        }
        $data["key-md2"] = Basic::kidTemp('md2');
        $data["key-md3"] = Basic::kidTemp('md3');
        $data["key-mdh"] = Basic::kidTemp('mdh');
        $data["key-5.5"] = Basic::kidTemp('5.5');
        $data["key-df1"] = Basic::kidTemp();
        $data["key-df2"] = Basic::kidTemp(1, '2022-06-22 14:48:31');
        $data["key-df3"] = Basic::kidTemp(1, 1658888678);

        $data["key-rnd1"] = Basic::kidRand(1);
        $data["key-rnd2"] = Basic::kidRand(1);
        $data["key-rnd3"] = Basic::kidRand(1);

        $data["key-fs1"] = Basic::kidRand('fs1');
        $data["key-fs2"] = Basic::kidRand('fs1');

        $this->api($data);
    }

    function readCfgsAct(){
        $data = ['act'=>__function__, 'msg'=>'read-配置。'];
        #$data['basic'] = read('basic');
        #$data['not_defined'] = read('not_defined'); // Warning
        $data['sy_mods'] = read('sy_mods');
        $data['sy_grade'] = read('sy_grade');
        $data['about'] = read('about');
        $data['info'] = read('info');
        $data['china'] = read('china');
        $data['world'] = read('world');
        $this->api($data);
    }

    # === test-123 =========================================== 

    function test1Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.Test'];
        //dump($data, __FILE__);
        $this->tpl($data, 'html1');
    }

    function test2Act(){
        $data = ['act'=>__function__, 'msg'=>'ysKit.Test'];
        //dump($data);
        $this->api($data);
    }

    # === db-data =========================================== 

    function defdbAct(){
        $data = ['act'=>__function__, 'msg'=>'DB操作-主数据库。'];
        $db = Dbop::db(); //dump($db->db);
        $data += $this->dbPub1Act($db);
        $this->api($data);
    }
    function dbPub1Act($db){
        $data['arr'] = $db->get("SELECT did,title,catid FROM {docs_info} WHERE catid='%s' LIMIT 3", ['i1012']);
        $data['row'] = $db->get("SELECT did,title,catid FROM {docs_info} WHERE catid='%s'", ['i1012'], 1);
        $data['val'] = $db->get("SELECT title,catid,click FROM {docs_info} WHERE catid='%s'", ["i1012"], 2);
        $data['count'] = $db->get("SELECT COUNT(*) FROM {docs_info} WHERE click>0", [], 2);
        $data['add'] = $db->run("INSERT INTO {xtest_keyid} (kid,kno,content,atime) VALUES ('".time()."','1','c1','".time()."')");
        $data['del'] = $db->run("DELETE FROM {xtest_keyid} WHERE kid='".time()."'");
        $data['sql1-inj'] = $db->get("SELECT title,click,catid FROM {docs_info} WHERE catid='%s' LIMIT 3", ["ad' or kid LIKE '%e%"]);
        $data['sql2-inj'] = $db->get("SELECT title,click,catid FROM {docs_info} WHERE catid='%s' LIMIT 3", ["ad \\ x"]);
        // TODO: count, sql-inject
        return $data;
    }
    function bakdbAct(){
        $data = ['act'=>__function__, 'msg'=>'DB操作-备份数据库。'];
        $db = Dbop::db('bak'); //dump($db->db);
        $data += $this->dbPub1Act($db);
        $this->api($data);
    }
    function outdbAct(){
        $data = ['act'=>__function__, 'msg'=>'DB操作-外部数据库。'];
        $db = Dbop::db('test'); //dump($db->db);
        #$db = Dbop::db(['db_name'=>'txblog_main']); //dump($db->db);
        $data['arr'] = $db->get("SELECT * FROM {users_uacc} WHERE uname LIKE '%yu%' LIMIT 3", []);
        $data['row1'] = $db->get("SELECT * FROM {users_uacc} WHERE uname LIKE '%s'", ["%yu%"], 1);
        $data['row2'] = $db->get("SELECT * FROM {users_uacc} WHERE uname LIKE '%s'", ["%ge%"], 1);
        $data['val'] = $db->get("SELECT * FROM {users_uacc} WHERE uname LIKE '%e'", [], 2);
        $data['count'] = $db->get("SELECT COUNT(*) FROM {users_uacc} WHERE ujifen>0", [], 2);
        $this->api($data);
    }

    # === pager =========================================== 

    function _viewAct(){
        $data = ['act'=>__function__, 'msg'=>'db-pager。'];
        $data['row'] = data('info.join', "did='{$this->mkvs['key']}'", 1);
        $mcfg = read('info'); $data['dic'] = $mcfg['i'];
        if($this->mkvs['part']=='api'){
            $this->api($data);
        }else{
            $this->tpl($data);
        }
    }

    function pagerAct(){
        $data = ['act'=>__function__, 'msg'=>'db-pager。'];
        $keywd = uval('keywd'); $whrk = $keywd ? " AND title LIKE '%$keywd%'" : '';
        $data = data('info', $whrk, '3.page');
        $mcfg = read('info'); $data['dic'] = $mcfg['i'];
        if($this->mkvs['part']=='api'){
            $this->api($data);
        }else{
            $this->tpl($data);
        }
    }

    function dbDataAct(){
        $data = ['act'=>__function__, 'msg'=>'db-data。'];
        #$data['not_db'] = data('china', '', '2,3'); // error:(HY000)
        $data['info-count'] = data('info', '', 'count'); 
        $data['info-row'] = data('info.join', '', 1);
        $data['info-arr'] = data('info', '', '2,3');
        $data['info-page'] = data('info', '', '3.page');
        //
        $this->api($data);
    }

    # === Adventure =========================================== 

    function upfileAct(){ 
        die('.end.');
        $up = new Upload();
        $res = [];
        $res['t1'] = $up->getRes();
        $up->saveRemote('https://www.dg165.com/static/assets/logo-web.png');
        $res['t2'] = $up->getRes();
        $b64data = file_get_contents(DIR_DATA.'/uptemp/_keep-base64-icon-test.txt');
        $up->upBase64(trim($b64data));
        $res['t3'] = $up->getRes();
        $this->api($res);
    }
    function imageAct(){ 
        die('.end.');
        $res = [];
        $img1 = 'E:/tmp-doc/di7-test-pics/zz-fuzh.jpg';
        $img2 = 'E:/tmp-doc/di7-test-pics/bar-code.png';

        $th1 = str_replace('.jpg', '-cut.jpg', $img1);
        $res['th1'] = Image::thumb($img1, $th1);
        $th2 = str_replace('.png', '-cut.png', $img2);
        $res['th2'] = Image::thumb($img2, $th2, 40, 30);

        /*
        $res['wm1a'] = Image::wmark($img1, 'pic');
        $res['wm1b'] = Image::wmark($img1, 'text');

        $res['wm2a'] = Image::wmark($img2, 'pic');
        $res['wm2b'] = Image::wmark($img2, 'text');
        */
        
        $this->api($res);
    }

    function pdfMarkAct(){
        require_once DIR_VENDOR . '/autoload.php';
        global $_cbase; 
        $base = DIR_DATA; // $_cbase['udir']['erpDt'];

        $fp1 = "/upfile/DemoPDF.pdf";
        $fp2 = "/upfile/DemoPDF-Res.pdf";

        $rnd = empty($_GET['rnd']) ? mt_rand(123,987) : $_GET['rnd']; // mt_rand(10088,98700)
        $mark = "MARK - $rnd"; 
        $demo = "YSKIT - DEMO - API"; #
        $sign = "PEACE - 2023-09-06"; #  

        $pdf = new setasign\Fpdi\Fpdi('L'); // $orientation='P', $unit='mm', $size='A4'
        $pdf->SetFont('Arial','B','24');//设置文字的字号字

        $pageCount = $pdf->SetSourceFile("$base/$fp1");
        for ($i=1; $i<=$pageCount; $i++) { //循环添加原始文件
            $tplId = $pdf->importPage($i);
            $size = $pdf->getTemplateSize($tplId); // 获取pdf的大小
            $pdf->AddPage('P'); // P 'L', [$size['width'],$size['height']]
            $pdf->useTemplate($tplId);
            $pdf->SetXY(120, 72); $pdf->Write(0, $mark); // 位置x，y，大小
            $pdf->SetXY(60, 180); $pdf->Write(0, $demo); // 位置x，y，大小
            $pdf->SetXY(80, 240); $pdf->Write(0, $sign); // 位置x，y，大小
            //
            //$pdf->SetFont('Arial','B','36');//设置文字的字号字
            //$pdf->Cell(20, 40, $demo, 0, 18); 
            // ($w, $h=0, $txt='',         $border=0, $ln=0, $align='', $fill=false, $link='')
            // ($w, $h, substr($s,$j,$i-$j),0,        2,     '',         false,$link);
            //$pdf->SetXY(50, 180); $pdf->Write(0, $wmk); // 位置x，y，大小
        }

        $pdf->Output("$base/$fp2", 'F'); // F-保存新文件, D-Down
        $vtext = "加文字(尺寸)-结果:<br>(".str_replace('   ',' &nbsp; &nbsp; ',$mark).")";
        echo "<p style='padding:1rem'><a href='{$_cbase['webRoot']}/data$fp2' target='_blank'>$demo</a></p>";

    }


}
